package com.qiwx.pigeon.fragment.produce;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DBSqlUtil;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.NumberUtil;
import com.qiwx.pigeon.Utils.StringUtil;
import com.qiwx.pigeon.activity.MainActivity;
import com.qiwx.pigeon.activity.produce.AddLayEggDateProduceActivity;
import com.qiwx.pigeon.base.Constant;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.params.CLZTParam;
import com.qiwx.pigeon.data.params.FertilizeParam;
import com.qiwx.pigeon.data.params.GETCLZTParam;
import com.qiwx.pigeon.data.params.LoseEggParam;
import com.qiwx.pigeon.data.params.PigeonDeathParam;
import com.qiwx.pigeon.data.vo.CageBeanVo;
import com.qiwx.pigeon.data.vo.CageRepairBean;
import com.qiwx.pigeon.data.vo.FertilizeBean;
import com.qiwx.pigeon.data.vo.pageinfo.PageInfo;
import com.qiwx.pigeon.widget.AddLayEggOptionView;
import com.qiwx.pigeon.widget.CageRepairOptionView;
import com.qiwx.pigeon.widget.CageStatusOptionView;
import com.qiwx.pigeon.widget.EliminateOptionView;
import com.qiwx.pigeon.widget.GridRadioGroup;
import com.qiwx.pigeon.widget.LoseEggOptionView;
import com.qiwx.pigeon.widget.PigeonDeathOptionView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qiwx.pigeon.activity.common.SelectDateActivity.REQUEST_CODE_START;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-29 16:52
 * 日常工段
 **/
public class DailyOperationFragment extends OpreateFragment {
    @BindView(R.id.rb_xdrq)
    RadioButton rbXdrq;
    @BindView(R.id.rb_Death)
    RadioButton rbDeath;
    @BindView(R.id.rb_clzt)
    RadioButton rbClzt;
    //    @BindView(R.id.rb_xtw)
//    RadioButton rbXtw;
    @BindView(R.id.rb_bfd)
    RadioButton rbBfd;
    @BindView(R.id.rb_repair)
    RadioButton rbRepair;
    @BindView(R.id.rb_taotai)
    RadioButton rb_taotai;
    @BindView(R.id.dg_preration)
    GridRadioGroup dgPreration;
    @BindView(R.id.lin_xdrq_date)
    LinearLayout linXdrqDate;
    @BindView(R.id.txt_start_date)
    TextView txtStartDate;
    @BindView(R.id.edt_cage_number)
    EditText edtCageNumber;
    @BindView(R.id.btn_opreation_ok)
    Button btnOpreationOk;
    @BindView(R.id.btn_opreation_cancel)
    Button btnOpreationCancel;
    @BindView(R.id.btn_opreation_add_date)
    Button btnOpreationAddDate;
    @BindView(R.id.lin_group_options)
    LinearLayout linGroupOptions;
    List<ViewGroup> listGroup = new ArrayList<>();
    int currentOperateID = 0;//当前操作模块id

    @BindView(R.id.add_lay_egg_options)
    AddLayEggOptionView addLayEggOptionView;
    @BindView(R.id.lose_egg_options)
    LoseEggOptionView loseEggOptionView;
    @BindView(R.id.cage_repair_options)
    CageRepairOptionView cageRepairOptionView;
    @BindView(R.id.cage_status_option)
    CageStatusOptionView cageStatusOptionView;
    @BindView(R.id.pigeon_death_option)
    PigeonDeathOptionView pigeonDeathOptionView;
    @BindView(R.id.cage_eliminate_options)
    EliminateOptionView cage_eliminate_options;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_daily_operation;
    }


    @Override
    public void initAfterOnCreate() {
        super.initAfterOnCreate();
        initView();
        initEvent();
        initGroupList();
    }

    private void initView() {
        btnOpreationCancel.setVisibility(View.GONE);
        btnOpreationAddDate.setVisibility(View.GONE);
        addLayEggOptionView.setShouJingShow(true);
    }

    private void resetXdrqDate() {
        txtStartDate.setText(DateTimeUtils.date2String(new Date()));
    }

    //下蛋日期
    private void selectXDRQ() {
        resetXdrqDate();
        btnOpreationAddDate.setVisibility(View.GONE);
        setGroupOptionsIsShow(0);
        addLayEggOptionView.resetOptions();

    }

    //鸽子死亡
    private void selectDeath() {
        btnOpreationAddDate.setVisibility(View.GONE);
        setGroupOptionsIsShow(1);
        pigeonDeathOptionView.resetOptions();

    }

    //存栏状态
    private void selectCLZT() {
        btnOpreationAddDate.setVisibility(View.GONE);
        setGroupOptionsIsShow(2);
        cageStatusOptionView.resetOptions();

    }


    //需调窝
//    private void selectXTW() {
//        btnOpreationAddDate.setVisibility(View.GONE);
//        setGroupOptionsIsShow(3);
//
//    }

    //不孵蛋
    private void selectBFD() {
        btnOpreationAddDate.setVisibility(View.GONE);
        //不显示选择项
//        setGroupOptionsIsShow(4);
        setGroupOptionsIsShow(3);

    }

    //踩破蛋
    private void selectCPT() {
        btnOpreationAddDate.setVisibility(View.GONE);
//        setGroupOptionsIsShow(5);
        setGroupOptionsIsShow(-1);

    }


    //鸽笼维修
    private void selectRepair() {
        btnOpreationAddDate.setVisibility(View.GONE);
        setGroupOptionsIsShow(4);
        cageRepairOptionView.resetOptions();

    }
    //鸽笼淘汰
    private void selectTaotai() {
        btnOpreationAddDate.setVisibility(View.GONE);
        setGroupOptionsIsShow(5);
        cageRepairOptionView.resetOptions();

    }

    private void initGroupList() {
        listGroup.add(addLayEggOptionView);
        listGroup.add(pigeonDeathOptionView);
        //groupCageStatusOptions
        listGroup.add(cageStatusOptionView);
//        listGroup.add(groupChangeCages);
        listGroup.add(loseEggOptionView);
        listGroup.add(cageRepairOptionView);
        listGroup.add(cage_eliminate_options);
        setGroupOptionsIsShow(-1);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (requestCode) {
//            case REQUEST_CODE_START:
//                if (data != null && !TextUtils.isEmpty(data.getStringExtra("car_Time_MSG"))) {
//                    txtStartDate.setText(data.getStringExtra("car_Time_MSG"));
//                }
//                break;
//        }
//    }

    private void changeRadioGroupIsShow(int pos) {
        for (int i = 0; i < listGroup.size(); i++) {
            if (i == pos) {
                listGroup.get(i).setVisibility(View.VISIBLE);
            } else {
                listGroup.get(i).setVisibility(View.GONE);
            }
        }
    }

    /*
     * 设置是否显示操作选项信息，有些操作需要，如鸽子死亡 选项需要用户选择几只
     *  type -1 都不显示
     * 0 鸽子死亡选项
     * 1 存栏状态选项
     * 2 鸽笼维修选项
     * 3 下蛋日期
     * */
    public void setGroupOptionsIsShow(int pos) {

        linXdrqDate.setVisibility(pos == 0 ? View.VISIBLE : View.GONE);
        for (int i = 0; i < listGroup.size(); i++) {
            if (i == pos) {
                listGroup.get(i).setVisibility(View.VISIBLE);
            } else {
                listGroup.get(i).setVisibility(View.GONE);
            }
        }

    }

    private void initEvent() {
        //用户选择哪个操作对象监听
        dgPreration.setOnCheckedChangeListener((group, checkId) -> {
            currentOperateID = checkId;
            switch (checkId) {
                case R.id.rb_xdrq://下蛋日期
                    selectXDRQ();
                    break;
                case R.id.rb_Death://鸽子死亡
                    selectDeath();
                    break;
                case R.id.rb_clzt://存栏状态
                    selectCLZT();
                    break;
//                case R.id.rb_xtw://需调窝
////                    selectXTW();
//                    break;
                case R.id.rb_bfd://不孵蛋
                    selectBFD();
                    break;
//                case R.id.rb_cpd://踩破蛋
//                    selectCPT();
                //break;
                case R.id.rb_repair://鸽笼维修
                    selectRepair();
                    break;
                case R.id.rb_taotai://淘汰鸽笼
                    selectTaotai();
                    break;
            }

        });

        txtStartDate.setOnClickListener(v -> {
            selectStartDate();
//            selectStartValiDate();
        });
        //鸽笼编号 键盘确认键监听
        edtCageNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId== EditorInfo.IME_ACTION_DONE){
                    save();
                }
                return false;
            }
        });

        edtCageNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                //获取个；鸽笼状态
                getCageState();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


    }

    @Override
    protected void onSelectDate(int type, String content) {

        //选择的时间
        long time =  DateTimeUtils.date2TimeStamp(content);
        //判断时间不能只能提前18天
        String cureettime =  DateTimeUtils.date2String(new Date());
        long cureet = DateTimeUtils.date2TimeStamp(cureettime);
        //18天前时间
        long sbTime = cureet-1555200000;
        if(time<sbTime){
            Toast.makeText(getActivity(),"选择时间不能提前18天",Toast.LENGTH_SHORT).show();
            return;
        }

        txtStartDate.setText(content);

    }



    //下蛋确认操作
    private void getCageState() {
        int c_number = 0;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }

        GETCLZTParam getclztParam = new GETCLZTParam();
        getclztParam.setC_number(c_number);
        getclztParam.setWh_id( MainActivity.wh_id);

        mPresenter.getCLZT(getclztParam);

    }



    //跳转补录下蛋日期
    private void goAddLayEggDate() {
        Intent go = new Intent();
        go.setClass(getActivity(), AddLayEggDateProduceActivity.class);
        String edtNumber = edtCageNumber.getText().toString();
        if (edtNumber != null && edtNumber.length() > 0) {
            int c_number = 0;
            try {
                c_number = Integer.valueOf(edtNumber);
            } catch (Exception e) {
                e.printStackTrace();
            }
            go.putExtra(Constant.INTENT_C_ID, 0);
            go.putExtra(Constant.INTENT_C_NUMBER, c_number);
        }
        go.putExtra(Constant.INTENT_WH_ID, MainActivity.wh_id);
        go.putExtra(Constant.INTENT_WH_NUMBER, MainActivity.wh_number);
//            go.putExtra("CageId", edtCageNumber.getText().toString());
        startActivity(go);
    }

    //下蛋日期如果选择空窝选项，则将鸽笼设置成空窝，并将生产表记录清空
    private void updateProdece(int wh_id, int cageNumber) {
        if (DBSqlUtil.updateProdece(wh_id, cageNumber)) {
            // rbEmpty.setChecked(false);
        }
    }

    //下蛋确认操作
    private void saveLayEgg() {
        int c_number = 0;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }
        FertilizeParam param = addLayEggOptionView.getParam();
        param.setWh_id(MainActivity.wh_id);
        param.setNumber(c_number);
        param.setLay_egg_date(txtStartDate.getText().toString());
        mPresenter.saveLayEgg(param);

    }


    //鸽崽死亡
    private void savePigeonDeath() {
        int c_number;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }
        PigeonDeathParam param = pigeonDeathOptionView.getParam();
        param.setWh_id(MainActivity.wh_id);
        param.setC_number(c_number);
        mPresenter.addPigeonDeath(param);

    }

    //存栏操作
    public void saveCLZT() {
        int c_number;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }
        CLZTParam param = cageStatusOptionView.getParam();
        param.setWh_id(MainActivity.wh_id);
        param.setC_number(c_number);

        mPresenter.changeCLZT(param);
    }

//    //是否需要调窝
//    public void saveNeedChangeCage() {
//        int c_number;
//        if ((c_number = checkCageNum(edtCageNumber.getText().toString())) <= 0) {
//            return;
//        }
//        CageBeanVo param = new CageBeanVo();
//        param.setWh_id(MainActivity.wh_id);
//        param.setNumber(c_number);
//        param.setIs_adjust(1);
//        mPresenter.changeCage(param);
//    }

    //不孵蛋 和踩破蛋 默认置成空窝
    public void saveBFD2BrokenEgg(int type) {
        int c_number;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }
        LoseEggParam param = loseEggOptionView.getParam();
        param.setWh_id(MainActivity.wh_id);
        param.setC_number(c_number);
        param.setAdd_date(DateTimeUtils.getCurrentDateStr());
        mPresenter.addEggLose(param);
    }

    //换窝布  鸽笼维修
    public void saveCageRepair() {
        int c_number;
        if ((c_number = NumberUtil.checkCageNum(edtCageNumber.getText().toString())) <= 0) {
            return;
        }
        CageRepairBean param = cageRepairOptionView.getParam();
        param.setWh_id(MainActivity.wh_id);
        param.setC_number(c_number);
        mPresenter.addCageRepair(param);
    }

    public void save() {
        switch (currentOperateID) {
            case R.id.rb_xdrq://下蛋日期
                saveLayEgg();
                break;
            case R.id.rb_Death://鸽子死亡
                savePigeonDeath();
                break;
            case R.id.rb_clzt://存栏状态
                saveCLZT();
                break;
//            case R.id.rb_xtw://需调窝
//                saveNeedChangeCage();
//                break;
            case R.id.rb_bfd://不孵蛋
                saveBFD2BrokenEgg(0);
                break;
//            case R.id.rb_cpd://踩破蛋
//                saveBFD2BrokenEgg(1);
//                break;
            case R.id.rb_repair://鸽笼维修
                saveCageRepair();
                break;


        }

    }

    @OnClick({R.id.btn_opreation_ok, R.id.btn_opreation_cancel, R.id.btn_opreation_add_date})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_opreation_ok:
                save();
                break;
            case R.id.btn_opreation_cancel:
                break;
            case R.id.btn_opreation_add_date:
//                goAddLayEggDate();
                break;
        }
    }

    @Override
    public void onCheckEggSuccess(PageInfo<FertilizeBean> list) {
        super.onCheckEggSuccess(list);
    }

    @Override
    public void onAddOperate(int type) {
        MyToast.showLong("操作成功");

        switch (type) {
            case ADD_TYPE_CLZT:
                cageStatusOptionView.resetOptions();
                break;
            case ADD_TYPE_ADD_PIGEON_DEATH:
                pigeonDeathOptionView.resetOptions();
                break;
            case ADD_TYPE_REPAIR:
                cageRepairOptionView.resetOptions();

                break;
            case ADD_TYPE_BFD_BROKEN:
                loseEggOptionView.resetOptions();
                break;
        }
        edtCageNumber.setText(null);
        rbXdrq.setChecked(true);
    }



    @Override
    public void onSaveLayEggSuccess(int c_id) {
        super.onSaveLayEggSuccess(c_id);
        addLayEggOptionView.resetOptions();
        resetXdrqDate();
        edtCageNumber.setText(null);
        MyToast.showLong("操作成功");
    }



    public static void  getCageStates(String respon){
        String s = respon;
    }

}
